<template>
  <el-card class="box-card" shadow="always">
    <div slot="header" class="clearfix">
      <span>{{ title }}</span>
      <el-button-group style="float: right;">
        <el-button
          v-if="!isShow"
          size="mini"
          icon="el-icon-plus"
          round
          :loading="loadingOptions.loading"
          :disabled="loadingOptions.isDisabled"
          @click="!data.id ? submitForm() : updateData()"
        >{{ loadingOptions.loadingText }}</el-button>
        <el-button size="mini" icon="el-icon-back" round @click="showCard">返回</el-button>
      </el-button-group>
    </div>
    <div class="body-wrapper">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" :disabled="isShow">
        <el-form-item label="数据源" prop="datasource">
          <el-select
            v-model="form.datasource"
            placeholder="数据源"
            style="width: 100%"
            @change="selectDataSource(form.datasourceGroup, form.datasource)"
          >
            <el-option v-for="item in dataSources" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据源名称" prop="datasourceName">
          <el-input v-model="form.datasourceName" placeholder="数据源名称" />
        </el-form-item>
        <el-form-item label="数据源分组" prop="datasourceGroup">
          <el-select
            v-model="form.datasourceGroup"
            placeholder="数据源分组"
            style="width: 100%"
            @change="myGroup(form.datasourceGroup, form.datasource)"
          >
            <el-option
              v-for="dict in sourceGroup"
              :key="dict.itemValue"
              :label="dict.itemText"
              :value="dict.itemValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="jdbc" label="用户名">
          <el-input v-model="form.jdbcUsername" placeholder="用户名" />
        </el-form-item>
        <el-form-item v-if="visible" v-show="jdbc" label="密码">
          <el-input v-model="form.jdbcPassword" type="password" placeholder="密码">
            <i slot="suffix" title="显示密码" style="cursor:pointer" class="el-icon-view" @click="changePass('show')" />
          </el-input>
        </el-form-item>
        <el-form-item v-show="jdbc" v-else label="密码">
          <el-input v-model="form.jdbcPassword" type="text" placeholder="密码">
            <i slot="suffix" title="隐藏密码" style="cursor:pointer" class="el-icon-check" @click="changePass('hide')" />
          </el-input>
        </el-form-item>
        <el-form-item v-if="jdbc" label="jdbc url" prop="jdbcUrl">
          <el-input v-model="form.jdbcUrl" :autosize="{ minRows: 3, maxRows: 6 }" type="textarea" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="mongodb" label="地址" prop="jdbcUrl">
          <el-input v-model="form.jdbcUrl" :autosize="{ minRows: 3, maxRows: 6 }" type="textarea" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="jdbc" label="jdbc驱动类" prop="jdbcDriverClass">
          <el-input v-model="form.jdbcDriverClass" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="orc" label="schema" prop="orcschema">
          <el-input v-model="form.orcschema" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="hbase" label="ZK地址" prop="zkAdress">
          <el-input v-model="form.zkAdress" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="mongodb" label="数据库名称" prop="databaseName">
          <el-input v-model="form.databaseName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="注释">
          <el-input v-model="form.comments" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="!isShow">
          <el-button type="primary" @click="testDataSource()">
            测试连接
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import * as datasourceApi from '@/api/integration/datax/datax-jdbcDatasource'

export default {
  name: 'JdbcDatasourceAdd',
  props: {
    data: {
      type: Object,
      default: function() {
        return {}
      }
    },
    title: { type: String, default: '新增数据源' },
    isShow: { type: Boolean, default: false }
  },
  data() {
    return {
      // 展示切换
      showOptions: {
        data: {},
        showList: true,
        showAdd: false,
        showEdit: false,
        showDetail: false
      },
      // 表单校验
      rules: {
        datasourceName: [{ required: true, message: '不能为空', trigger: 'blur' }],
        jdbcUsername: [{ required: true, message: '不能为空', trigger: 'blur' }],
        jdbcPassword: [{ required: true, message: '不能为空', trigger: 'blur' }],
        jdbcUrl: [{ required: true, message: '不能为空', trigger: 'blur' }],
        jdbcDriverClass: [{ required: true, message: '不能为空', trigger: 'blur' }],
        datasource: [{ required: true, message: '不能为空', trigger: 'change' }],
        zkAdress: [{ required: true, message: '不能为空', trigger: 'blur' }],
        databaseName: [{ required: true, message: '不能为空', trigger: 'blur' }],
        orcschema: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      // 保存按钮
      loadingOptions: {
        loading: false,
        loadingText: '保存',
        isDisabled: false
      },
      // 表单参数
      form: {
        datasourceName: '',
        jdbcUsername: '',
        datasourceGroup: '',
        jdbcUrl: '',
        jdbcDriverClass: '',
        jdbcPassword: '',
        datasource: '',
        zkAdress: '',
        databaseName: '',
        orcschema: '',
        comments: '',
      },
      dataSources: [
        { value: 'mysql', label: 'mysql' },
        { value: 'oracle', label: 'oracle' },
        { value: 'postgresql', label: 'postgresql' },
        { value: 'sqlserver', label: 'sqlserver' },
        { value: 'hive', label: 'hive' },
        { value: 'hbase', label: 'hbase' },
        { value: 'mongodb', label: 'mongodb' },
        { value: 'clickhouse', label: 'clickhouse' }
      ],
      sourceGroup: [],
      jdbc: true,
      visible: true,
      hbase: false,
      mongodb: true,
      orc: false
    }
  },
  created() {
    this.getDicts('source_group').then(response => {
      if (response.success) {
        this.sourceGroup = response.data
      }
    })
    if (this.data.id) {
      this.jdbcDatasource(this.data.id)
    }
  },
  methods: {
    showCard() {
      this.$emit('showCard', this.showOptions)
    },
    jdbcDatasource(id) {
      datasourceApi.getjobJdbcDatasource(id).then(response => {
        if (response.success) {
          this.form = response.data
        }
      })
    },
    selectDataSource(myGroup, datasource) {
      if (datasource === 'mysql') {
        if (myGroup === 'warehouse_building') {
          this.form.jdbcUrl = 'jdbc:mysql://{host}:{port}/'
        } else {
          this.form.jdbcUrl = 'jdbc:mysql://{host}:{port}/{database}'
        }
        this.form.jdbcDriverClass = 'com.mysql.jdbc.Driver'
      } else if (datasource === 'oracle') {
        if (myGroup === 'warehouse_building') {
          this.form.jdbcUrl = 'jdbc:oracle:thin:@//{host}:{port}/'
        } else {
          this.form.jdbcUrl = 'jdbc:oracle:thin:@//{host}:{port}/{database}'
        }
        this.form.jdbcDriverClass = 'oracle.jdbc.OracleDriver'
      } else if (datasource === 'postgresql') {
        if (myGroup === 'warehouse_building') {
          this.form.jdbcUrl = 'jdbc:postgresql://{host}:{port}/'
        } else {
          this.form.jdbcUrl = 'jdbc:postgresql://{host}:{port}/{database}'
        }
        this.form.jdbcDriverClass = 'org.postgresql.Driver'
      } else if (datasource === 'sqlserver') {
        if (myGroup === 'warehouse_building') {
          this.form.jdbcUrl = 'jdbc:sqlserver://{host}:{port};'
        } else {
          this.form.jdbcUrl = 'jdbc:sqlserver://{host}:{port};DatabaseName={database}'
        }
        this.form.jdbcDriverClass = 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
      } else if (datasource === 'clickhouse') {
        if (myGroup === 'warehouse_building') {
          this.form.jdbcUrl = 'jdbc:clickhouse://{host}:{port}/'
        } else {
          this.form.jdbcUrl = 'jdbc:clickhouse://{host}:{port}/{database}'
        }
        this.form.jdbcDriverClass = 'ru.yandex.clickhouse.ClickHouseDriver'
      } else if (datasource === 'hive') {
        if (myGroup === 'warehouse_building') {
          this.form.jdbcUrl = 'jdbc:hive2://{host}:{port}/'
        } else {
          this.form.jdbcUrl = 'jdbc:hive2://{host}:{port}/{database}'
        }
        this.form.jdbcDriverClass = 'org.apache.hive.jdbc.HiveDriver'
        this.hbase = this.mongodb = false
        this.jdbc = true
      }
      this.getShowStrategy(datasource)
    },
    getShowStrategy(datasource) {
      if (datasource === 'hbase') {
        this.jdbc = this.mongodb = false
        this.hbase = true
      } else if (datasource === 'mongodb') {
        this.jdbc = this.hbase = false
        this.mongodb = true
        this.form.jdbcUrl = 'mongodb://[username:password@]host1[:port1][,...hostN[:portN]]][/[database][?options]]'
      } else if (datasource === 'oracle') {
        this.orc = true
        this.mongodb = false
      } else {
        this.hbase = this.mongodb = this.orc = false
        this.jdbc = true
      }
    },
    myGroup(myGroup, datasource) {
      if (datasource === 'mysql') {
        if (myGroup === 'warehouse_building') {
          this.form.jdbcUrl = 'jdbc:mysql://{host}:{port}/'
        } else {
          this.form.jdbcUrl = 'jdbc:mysql://{host}:{port}/{database}'
        }
        this.form.jdbcDriverClass = 'com.mysql.jdbc.Driver'
      } else if (datasource === 'oracle') {
        if (myGroup === 'warehouse_building') {
          this.form.jdbcUrl = 'jdbc:oracle:thin:@//{host}:{port}/'
        } else {
          this.form.jdbcUrl = 'jdbc:oracle:thin:@//{host}:{port}/{database}'
        }
        this.form.jdbcDriverClass = 'oracle.jdbc.OracleDriver'
      } else if (datasource === 'postgresql') {
        if (myGroup === 'warehouse_building') {
          this.form.jdbcUrl = 'jdbc:postgresql://{host}:{port}/'
        } else {
          this.form.jdbcUrl = 'jdbc:postgresql://{host}:{port}/{database}'
        }
        this.form.jdbcDriverClass = 'org.postgresql.Driver'
      } else if (datasource === 'sqlserver') {
        if (myGroup === 'warehouse_building') {
          this.form.jdbcUrl = 'jdbc:sqlserver://{host}:{port};'
        } else {
          this.form.jdbcUrl = 'jdbc:sqlserver://{host}:{port};DatabaseName={database}'
        }
        this.form.jdbcDriverClass = 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
      } else if (datasource === 'clickhouse') {
        if (myGroup === 'warehouse_building') {
          this.form.jdbcUrl = 'jdbc:clickhouse://{host}:{port}/'
        } else {
          this.form.jdbcUrl = 'jdbc:clickhouse://{host}:{port}/{database}'
        }
        this.form.jdbcDriverClass = 'ru.yandex.clickhouse.ClickHouseDriver'
      } else if (datasource === 'hive') {
        if (myGroup === 'warehouse_building') {
          this.form.jdbcUrl = 'jdbc:hive2://{host}:{port}/'
        } else {
          this.form.jdbcUrl = 'jdbc:hive2://{host}:{port}/{database}'
        }
        this.form.jdbcDriverClass = 'org.apache.hive.jdbc.HiveDriver'
        this.hbase = this.mongodb = false
        this.jdbc = true
      }
      this.getShowStrategy(datasource)
    },
    changePass(value) {
      this.visible = !(value === 'show')
    },
    testDataSource() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          datasourceApi.test(this.form).then(response => {
            if (response.data === false) {
              this.$notify({
                title: 'Fail',
                message: response.data.msg,
                type: 'fail',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'Success',
                message: 'Tested Successfully',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loadingOptions.loading = true
          this.loadingOptions.loadingText = '保存中...'
          this.loadingOptions.isDisabled = true
          datasourceApi.created(this.form).then(response => {
            if (response.success) {
              this.$message.success('保存成功')
              setTimeout(() => {
                // 2秒后跳转列表页
                this.$emit('showCard', this.showOptions)
              }, 2000)
            } else {
              this.$message.error('保存失败')
              this.loadingOptions.loading = false
              this.loadingOptions.loadingText = '保存'
              this.loadingOptions.isDisabled = false
            }
          }).catch(() => {
            this.loadingOptions.loading = false
            this.loadingOptions.loadingText = '保存'
            this.loadingOptions.isDisabled = false
          })
        }
      })
    },
    // 更新数据
    updateData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.form)
          datasourceApi.updated(tempData).then((response) => {
            if (response.success) {
              this.$message.success('保存成功')
              setTimeout(() => {
                // 2秒后跳转列表页
                this.$emit('showCard', this.showOptions)
              }, 2000)
            } else {
              this.$message.error('保存失败')
              this.loadingOptions.loading = false
              this.loadingOptions.loadingText = '保存'
              this.loadingOptions.isDisabled = false
            }
          }).catch(() => {
            this.loadingOptions.loading = false
            this.loadingOptions.loadingText = '保存'
            this.loadingOptions.isDisabled = false
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card ::v-deep .el-card__body {
  height: calc(100vh - 230px);
  overflow-y: auto;
}
</style>
